package com.wgh.demo.ai.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.wgh.demo.ai.entity.Stock;
import com.wgh.demo.ai.repository.StockRepository;
import com.wgh.demo.ai.service.StockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CompletableFuture;

@Service
public class StockServiceImpl implements StockService {

    private static final Logger logger = LoggerFactory.getLogger(StockServiceImpl.class);
    private final StockRepository stockRepository;

    @Autowired
    public StockServiceImpl(StockRepository stockRepository) {
        this.stockRepository = stockRepository;
    }

    @Override
    public List<Stock> findAll() {
        return stockRepository.findAll();
    }

    @Override
    public Page<Stock> findAll(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return stockRepository.findAll(pageable);
    }

    @Override
    public Flux<Stock> findAllReactive(int page, int size) {
        return Flux.defer(() -> {
            Pageable pageable = PageRequest.of(page, size);
            List<Stock> stocks = stockRepository.findAll(pageable).getContent();
            return Flux.fromIterable(stocks);
        });
    }

    @Override
    public Flux<Stock> findAllReactiveWithoutPagination() {
        return Flux.defer(() -> {
            List<Stock> stocks = stockRepository.findAll();
            return Flux.fromIterable(stocks);
        });
    }

    @Override
    public Mono<Page<Stock>> findAllReactivePage(int page, int size) {
        return Mono.fromCallable(() -> {
            Pageable pageable = PageRequest.of(page, size);
            return stockRepository.findAll(pageable);
        });
    }

    @Override
    public Stock findById(Long id) {
        return stockRepository.findById(id).orElse(null);
    }

    @Override
    public Stock save(Stock stock) {
        return stockRepository.save(stock);
    }

    @Override
    public void deleteById(Long id) {
        stockRepository.deleteById(id);
    }

    @Override
    public boolean existsByCode(String code) {
        return stockRepository.existsByCode(code);
    }

    @Override
    public StockService.ImportResult importStocksFromCsv(byte[] csvData) {
        int successCount = 0;
        int failCount = 0;

        logger.info("开始导入股票数据，数据长度: {}", csvData.length);

        try {
            // 直接使用字节数组解析CSV，避免创建临时文件
            String csvContent = new String(csvData, "UTF-8");
            logger.info("CSV内容预览: {}", csvContent.substring(0, Math.min(100, csvContent.length())));

            // 按行分割CSV内容
            String[] lines = csvContent.split("\\r?\\n");
            logger.info("CSV文件共有 {} 行", lines.length);

            for (String line : lines) {
                if (line.trim().isEmpty()) {
                    continue; // 跳过空行
                }

                logger.info("处理CSV行: {}", line);
                String[] parts = line.split(",");

                if (parts == null || parts.length < 2) {
                    logger.warn("行数据列数不足: {}", line);
                    failCount++;
                    continue;
                }

                String name = parts[0].trim();
                String code = parts[1].trim();

                logger.info("处理股票: 名称={}, 代码={}", name, code);

                try {
                    Stock existingStock = stockRepository.findByCode(code);
                    if (existingStock != null) {
                        // 更新现有股票
                        logger.info("更新现有股票: {}", code);
                        existingStock.setName(name);
                        stockRepository.save(existingStock);
                        successCount++;
                    } else {
                        // 创建新股票
                        logger.info("创建新股票: {}", code);
                        Stock newStock = new Stock();
                        newStock.setName(name);
                        newStock.setCode(code);
                        stockRepository.save(newStock);
                        successCount++;
                    }
                } catch (Exception e) {
                            failCount++;
                            logger.error("处理股票失败: {} - {}", code, e.getMessage(), e);
                        }
            }

            logger.info("CSV数据解析完成");
        } catch (Exception e) {
            logger.error("解析CSV文件失败: {}", e.getMessage(), e);
            failCount++;
        }

        logger.info("股票导入完成: 成功={}, 失败={}", successCount, failCount);
        return new StockService.ImportResult(successCount, failCount);
    }
}